const express = require('express');
const router = express.Router();
const Tour = require('../models/Tour');

// 获取所有旅游商品
router.get('/', async (req, res) => {
  try {
    const { 
      category, 
      destination, 
      minPrice, 
      maxPrice, 
      isHot, 
      page = 1, 
      limit = 10,
      sortBy = 'createdAt',
      sortOrder = 'desc'
    } = req.query;

    // 构建查询条件
    const query = {};
    
    if (category) query.category = category;
    if (destination) query.destination = new RegExp(destination, 'i');
    if (minPrice || maxPrice) {
      query.price = {};
      if (minPrice) query.price.$gte = Number(minPrice);
      if (maxPrice) query.price.$lte = Number(maxPrice);
    }
    if (isHot !== undefined) query.isHot = isHot === 'true';

    // 构建排序
    const sort = {};
    sort[sortBy] = sortOrder === 'desc' ? -1 : 1;

    // 分页参数
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    // 执行查询
    const tours = await Tour.find(query)
      .sort(sort)
      .skip(skip)
      .limit(limitNum);

    // 获取总数
    const total = await Tour.countDocuments(query);

    res.json({
      success: true,
      data: tours,
      pagination: {
        page: pageNum,
        limit: limitNum,
        total,
        pages: Math.ceil(total / limitNum)
      }
    });
  } catch (error) {
    console.error('获取旅游商品失败:', error);
    res.status(500).json({
      success: false,
      message: '获取旅游商品失败',
      error: error.message
    });
  }
});

// 根据分类获取商品
router.get('/category/:category', async (req, res) => {
  try {
    const { category } = req.params;
    const { page = 1, limit = 10 } = req.query;

    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    const tours = await Tour.find({ category })
      .sort({ isHot: -1, soldCount: -1 })
      .skip(skip)
      .limit(limitNum);

    const total = await Tour.countDocuments({ category });

    res.json({
      success: true,
      data: tours,
      pagination: {
        page: pageNum,
        limit: limitNum,
        total,
        pages: Math.ceil(total / limitNum)
      }
    });
  } catch (error) {
    console.error('获取分类商品失败:', error);
    res.status(500).json({
      success: false,
      message: '获取分类商品失败',
      error: error.message
    });
  }
});

// 获取热门商品
router.get('/hot', async (req, res) => {
  try {
    const { limit = 6 } = req.query;
    
    const tours = await Tour.find({ isHot: true })
      .sort({ soldCount: -1 })
      .limit(parseInt(limit));

    res.json({
      success: true,
      data: tours
    });
  } catch (error) {
    console.error('获取热门商品失败:', error);
    res.status(500).json({
      success: false,
      message: '获取热门商品失败',
      error: error.message
    });
  }
});

// 获取商品详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const tour = await Tour.findById(id);
    
    if (!tour) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }

    res.json({
      success: true,
      data: tour
    });
  } catch (error) {
    console.error('获取商品详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取商品详情失败',
      error: error.message
    });
  }
});

// 获取商品分类统计
router.get('/stats/categories', async (req, res) => {
  try {
    const stats = await Tour.aggregate([
      {
        $group: {
          _id: '$category',
          count: { $sum: 1 },
          avgPrice: { $avg: '$price' },
          minPrice: { $min: '$price' },
          maxPrice: { $max: '$price' }
        }
      },
      {
        $sort: { count: -1 }
      }
    ]);

    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    console.error('获取分类统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取分类统计失败',
      error: error.message
    });
  }
});

module.exports = router; 